package com.bw.server.device

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.base.path.RouterPath
import com.bw.common.event.CustomEvent
import com.bw.common.utils.DialogUtils
import com.bw.common.view.BaseMvvmActivity
import com.bw.server.R
import com.bw.server.adapter.DeviceAdapter
import com.bw.server.databinding.ActivityDeviceBinding
import com.bw.server.vm.ServerViewModel
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 *
 * 设备管理页面
 */
@Route(path = RouterPath.PATH_DEVICE_PATH)
@AndroidEntryPoint
class DeviceActivity : BaseMvvmActivity<ActivityDeviceBinding>() {


    override fun getLayoutId(): Int = R.layout.activity_device

    val deviceAdapter = DeviceAdapter()

    private val mViewModel:ServerViewModel by viewModels()

    override fun initViews() {
        super.initViews()
        //点击返回
        mDataBinding.back.setOnClickListener {
            finish()
        }
        //列表绑定适配器
        mDataBinding.rv.adapter = deviceAdapter

        //点击+  跳转到添加设备页面
        mDataBinding.addDevice.setOnClickListener {
            ARouter.getInstance().build("/server/AddDeviceActivity").navigation()
        }
        //点击设备  跳转到设备详情页面
        deviceAdapter.setOnItemClickListener { adapter, view, position ->
            //跳转 传id
            ARouter.getInstance().build(RouterPath.PATH_DEVICE_DETAIL_NORMAL)
                .withInt("did",deviceAdapter.data[position].id)
                .withString("dInspector",deviceAdapter.data[position].inspector)
                .navigation()
        }

    }

    override fun onResume() {
        super.onResume()
        mViewModel.getDeviceData()
    }

    override fun loadData() {
        super.loadData()

        mViewModel.getDeviceData()
    }

    override fun observeDataChanged() {
        super.observeDataChanged()
        //请求成功数据 展示
        mViewModel.mSuccess.observe(this){
            deviceAdapter.data.clear()
            deviceAdapter.data.addAll(it.reversed())
            deviceAdapter.notifyDataSetChanged()
        }
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCusEventBus(event: CustomEvent){
        if(event.target == RouterPath.PATH_DEVICE_PATH){
            if (event.type == 1){
                mViewModel.getDeviceData()
            }
        }

    }

}